package com.saikuo.service.dao.impl;

import com.saikuo.service.dao.IAdvertisementDao;
import com.saikuo.service.vo.BannerView;
import com.saikuo.service.vo.CategoryView;
import com.saikuo.service.vo.PostageView;
import com.saikuo.service.vo.TopicSaleView;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.util.Collections;
import java.util.List;

/**
 * Created by chenzhuo on 16/7/25.
 */
@Repository
public class AdvertisementDaoImpl extends JdbcDaoSupport implements IAdvertisementDao {

    private static final BeanPropertyRowMapper<BannerView> mapper = new
            BeanPropertyRowMapper<>(BannerView.class);
    private static final BeanPropertyRowMapper<CategoryView> mapperCategory = new
            BeanPropertyRowMapper<>(CategoryView.class);
    private static final BeanPropertyRowMapper<TopicSaleView> mapperTopicSale = new
            BeanPropertyRowMapper<>(TopicSaleView.class);
    private static final BeanPropertyRowMapper<PostageView> mapperPostage = new
            BeanPropertyRowMapper<>(PostageView.class);
    @Autowired
    AdvertisementDaoImpl(DataSource dataSource) {
        setDataSource(dataSource);
    }


    private static final String GET_BANNER = "select id,pic_url,content_url from " +
            "y_banner where status=0";

    @Override
    public List<BannerView> getBanner() {
        List<BannerView> result = this.getJdbcTemplate().query(GET_BANNER, mapper);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result;
    }

    private static final String GET_CATEGORY = "select * from y_category order by level";

    @Override
    public List<CategoryView> getCategory() {
        List<CategoryView> result = this.getJdbcTemplate().query(GET_CATEGORY, mapperCategory);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result;
    }

    private static final String GET_TOPIC_SALE = "select id,pic_url,title,medicine_ids,location from y_topic_sale";

    @Override
    public List<TopicSaleView> getTopicSale() {
        List<TopicSaleView> result = this.getJdbcTemplate().query(GET_TOPIC_SALE, mapperTopicSale);
        if (CollectionUtils.isEmpty(result)) {
            return Collections.emptyList();
        }
        return result;
    }

    private static final String GET_POSTAGE = "select * from y_postage";
    @Override
    public PostageView getPostageView(){
        List<PostageView> result = this.getJdbcTemplate().query(GET_POSTAGE, mapperPostage);
        if (CollectionUtils.isNotEmpty(result)) {
            return result.get(0);
        }
        return null;
    }
}
